package com.czy.owner.ui.archive;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.czy.otherlib.wheelview.adapters.ArrayWheelAdapter;
import com.czy.otherlib.wheelview.widget.OnWheelScrollListener;
import com.czy.otherlib.wheelview.widget.WheelView;
import com.czy.owner.R;
import com.czy.owner.adapter.ArchiveTypeAdapter;
import com.czy.owner.adapter.BaseRecyclerAdapter;
import com.czy.owner.entity.CarArchiveType;
import com.czy.owner.entity.CarInfo;
import com.czy.owner.global.Constants;
import com.czy.owner.db.UserHelper;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.CashierInputFilter;
import com.czy.owner.utils.InitKeyBoardContext;
import com.czy.owner.utils.KeyboardUtils;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.disk.DiskLruCacheHelper;
import com.czy.owner.widget.PageTitleView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;

/**
 * Created by King on 2016/6/23 0023.
 * 添加记录
 */
public class ArchiveAddActivity extends BaseActivity {
    private final String TAG = getClass().getSimpleName();

    public PageTitleView pageTitle;
    public String carFilesRecordId = "";
    @BindView(R.id.et_archive_add_type)
    EditText etType;
    @BindView(R.id.iv_archive_add_type)
    ImageView ivType;
    @BindView(R.id.et_archive_add_date)
    EditText etDate;
    @BindView(R.id.et_archive_add_amount)
    EditText etAmount;
    @BindView(R.id.et_archive_add_mileage)
    EditText etMileage;
    @BindView(R.id.et_archive_add_remark)
    EditText etRemark;
    @BindView(R.id.btn_car_archive_add)
    Button btnAdd;

    private Dialog mTypeDialog, mDateDialog;
    private ArchiveTypeAdapter mArchiveTypeAdapter;
    public boolean interceptLongClick = true;
    private int currentYear, currentMonth, currentDay;
    private CarInfo mCarInfo;
    public CarArchiveType mArchiveType;
    private DiskLruCacheHelper cacheHelper;
    private List<CarArchiveType> archiveTypeList = new ArrayList<>();
    private final String CACHE_KEY = "czy_archive_type";
    public String successToast = "添加记录成功";

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_archive_add;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        if (getIntent().getExtras() == null || (mCarInfo = (CarInfo) getIntent().getSerializableExtra(Constants.TRANSMISSION_CONTENT_KEY)) == null) {
            PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "参数异常!");
            finish();
            return;
        }
        try {
            cacheHelper = new DiskLruCacheHelper(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        pageTitle = new PageTitleView((RelativeLayout) findViewById(R.id.rl_page_title), "记一笔", true);
        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR);
        currentMonth = c.get(Calendar.MONTH) + 1;
        currentDay = c.get(Calendar.DAY_OF_MONTH);
        String txtMonth = "0" + currentMonth, txtDay = "0" + currentDay;
        txtMonth = txtMonth.substring(txtMonth.length() - 2);
        txtDay = txtDay.substring(txtDay.length() - 2);
//        etDate.setText(currentYear + "-" + txtMonth + "-" + txtDay);
        getArchiveTypeData();
        initListener();


        InputFilter[] filters = {new CashierInputFilter(9), new InputFilter.LengthFilter(9)};
        etAmount.setFilters(filters);
    }

    @Override
    protected void updateViews() {

    }


    private void initListener() {
        pageTitle.getLeftButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        etType.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return interceptLongClick;
            }
        });
        ivType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTypeDialog();
            }
        });
        etDate.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        etDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDateDialog();
            }
        });

        etAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                int d = temp.indexOf(".");
                if (d < 0) return;
                if (temp.length() - d - 1 > 2) {
                    s.delete(d + 3, d + 4);
                } else if (d == 0) {
                    s.delete(d, d + 1);
                }
            }
        });
        /*etSelectArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog = new Dialog(ArchiveAddActivity.this, R.style.AlertDialogStyle);
                mDialog.setContentView(LayoutInflater.from(ArchiveAddActivity.this).inflate(
                        R.layout.dialog_select_area, null));
                mDialog.show();
            }
        });*/
        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mArchiveType == null) {
                    PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "请选择消费类型");
                    // showTypeDialog();
                    return;
                }
                if (mArchiveType.getCarFilesCostTypeId() == -1 && TextUtils.isEmpty(etType.getText().toString().trim())) {
                    PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "请输入自定义消费类型");
                    etType.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(etDate.getText().toString())) {
                    PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "请选择消费日期");
                    //  showDateDialog();
                    return;
                }
                Calendar tmpCalendar = Calendar.getInstance();
                Date date = null;
                DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm");
                try {
                    date = formatter.parse(etDate.getText().toString() + " 00:00");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if (date == null) {
                    PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "请选择消费日期");
                    showDateDialog();
                    return;
                }
                if (date.getTime() > tmpCalendar.getTimeInMillis()) {
                    PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "消费日期错误");
                    showDateDialog();
                    return;
                }
                if (TextUtils.isEmpty(etAmount.getText().toString())) {
                    PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "请输入消费金额");
                    etAmount.requestFocus();
                    return;
                }
                if (TextUtils.isEmpty(etMileage.getText().toString())) {
                    PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "请输入行驶公里数");
                    etMileage.requestFocus();
                    return;
                }

                btnAdd.setEnabled(false);
                mLoadView.ShowLoadView("数据提交中...");
                RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_SAVE_RECORD);
                params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(ArchiveAddActivity.this).getSession());
                MyLog.e("hep", mCarInfo.getOwnerCarId() + "");
                params.addBodyParameter("ownerCarId", "" + mCarInfo.getOwnerCarId());
                if (mArchiveType.getCarFilesCostTypeId() == -1) {
                    params.addBodyParameter("carFilesCostTypeName", "" + etType.getText().toString().trim());
                } else {
                    params.addBodyParameter("carFilesCostTypeId", "" + mArchiveType.getCarFilesCostTypeId());
                }

                params.addBodyParameter("carFilesRecordId", carFilesRecordId + "");

                params.addBodyParameter("serviceTime", "" + etDate.getText().toString());
                params.addBodyParameter("price", "" + etAmount.getText().toString());
                params.addBodyParameter("mileage", "" + etMileage.getText().toString());
                params.addBodyParameter("note", "" + etRemark.getText().toString().trim());

                x.http().post(params, new Callback.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String result) {
                        String data = PhoneUtils.checkResponseFlag(ArchiveAddActivity.this, result);
                        if (data != null) {
                            PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, successToast);
                            setResult(RESULT_OK);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "数据提交异常,请重试!");
                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {
                        mLoadView.CancleLoadView();
                        btnAdd.setEnabled(true);
                    }
                });
            }
        });
    }

    private void getArchiveTypeData() {
        String cacheData = null;
        if (cacheHelper != null) {
            //cacheData = cacheHelper.getAsString(CACHE_KEY);
        }

        if (cacheData == null || TextUtils.isEmpty(cacheData) || "[]".equals(cacheData)) {
            mLoadView.ShowLoadView(getResources().getString(R.string.refresh_loading));
            RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_CAR_COST_TYPE);
            params.addBodyParameter("session", UserHelper.getInstance().getSessionInfoModel(this).getSession());
            x.http().post(params, new Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String result) {
                    String data = PhoneUtils.checkResponseFlag(ArchiveAddActivity.this, result);
                    if (data != null) {
                        cacheHelper.put(CACHE_KEY, data);
                        archiveTypeList = new Gson().fromJson(data, new TypeToken<List<CarArchiveType>>() {
                        }.getType());
                        CarArchiveType mType = new CarArchiveType();
                        mType.setCarFilesCostTypeId(-1);
                        mType.setSort(9999);
                        mType.setTypeName("自定义");
                        archiveTypeList.add(mType);
                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {

                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    mLoadView.CancleLoadView();
                }
            });
        } else {
            archiveTypeList = new Gson().fromJson(cacheData, new TypeToken<List<CarArchiveType>>() {
            }.getType());
            CarArchiveType mType = new CarArchiveType();
            mType.setCarFilesCostTypeId(-1);
            mType.setSort(9999);
            mType.setTypeName("自定义");
            archiveTypeList.add(mType);
        }
    }

    private void showTypeDialog() {
        if (mTypeDialog == null) {
            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            Display mDisplay = windowManager.getDefaultDisplay();
            mTypeDialog = new Dialog(ArchiveAddActivity.this, R.style.AlertDialogStyle);
            View dialogView = LayoutInflater.from(ArchiveAddActivity.this).inflate(R.layout.dialog_archive_add_type, null);
            Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);
            btnSure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mArchiveTypeAdapter.getSelectedArchiveType() != null) {
                        mArchiveType = mArchiveTypeAdapter.getSelectedArchiveType();
                        if (mArchiveTypeAdapter.getSelectedArchiveType().getCarFilesCostTypeId() == -1) {
                            interceptLongClick = false;
                            etType.setFocusable(true);
                            etType.setFocusableInTouchMode(true);
                            etType.requestFocus();
                            if (!mArchiveTypeAdapter.isCustom())
                                etType.setText("");

                        } else {
                            etType.setText(mArchiveTypeAdapter.getSelectedArchiveType().getTypeName());
                            interceptLongClick = true;
                            etType.setFocusable(false);
                            etType.setFocusableInTouchMode(false);
                        }
                    }
                    mTypeDialog.dismiss();
                    if (mArchiveTypeAdapter.getSelectedArchiveType() != null && mArchiveTypeAdapter.getSelectedArchiveType().getCarFilesCostTypeId() == -1) {
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                InitKeyBoardContext.init(ArchiveAddActivity.this);
                                KeyboardUtils.showSoftInput(etType);
                            }
                        }, 100);

                    }
                }
            });

            RecyclerView rvAddType = (RecyclerView) dialogView.findViewById(R.id.rv_archive_add_type);
            RecyclerView.LayoutManager layoutManager = new GridLayoutManager(ArchiveAddActivity.this, 3);
            rvAddType.setLayoutManager(layoutManager);
            mArchiveTypeAdapter = new ArchiveTypeAdapter(ArchiveAddActivity.this, archiveTypeList);
            mArchiveTypeAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<CarArchiveType>() {
                @Override
                public void onItemClick(int position, CarArchiveType o, View view) {
                    mArchiveTypeAdapter.setSelectedArchiveType(o);
                    mArchiveTypeAdapter.notifyDataSetChanged();
                }
            });
            rvAddType.setAdapter(mArchiveTypeAdapter);

            mTypeDialog.setContentView(dialogView);
            mTypeDialog.setCancelable(true);
            mTypeDialog.setCanceledOnTouchOutside(true);

            Window dialogWindow = mTypeDialog.getWindow();
            WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
            p.width = (int) (mDisplay.getWidth() * 0.86);
            dialogWindow.setAttributes(p);
        }
        //mArchiveTypeAdapter.setSelectedArchiveType(etType.getText().toString().trim());
        mArchiveTypeAdapter.notifyDataSetChanged();
        if (mArchiveType != null) {
            mArchiveTypeAdapter.setSelectedArchiveType(mArchiveType);
            mArchiveTypeAdapter.setCustom(mArchiveType.getCarFilesCostTypeId() == -1);
        }
        mTypeDialog.show();
    }

    private void showDateDialog() {
        int yearIndex = 0, monthIndex = currentMonth - 1, dayIndex = currentDay - 1;
        Calendar tmpCalendar = Calendar.getInstance();
        Date date = null;
        if (!TextUtils.isEmpty(etDate.getText())) {
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = formatter.parse(etDate.getText().toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
            if (date != null) {
                tmpCalendar.setTime(date);
            }
        }
        WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display mDisplay = windowManager.getDefaultDisplay();
        mDateDialog = new Dialog(ArchiveAddActivity.this, R.style.AlertDialogStyle);
        View dialogView = LayoutInflater.from(ArchiveAddActivity.this).inflate(R.layout.dialog_archive_add_date, null);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure);

        final WheelView wvYear, wvMonth, wvDay;
        wvYear = (WheelView) dialogView.findViewById(R.id.wv_archive_date_year);
        wvMonth = (WheelView) dialogView.findViewById(R.id.wv_archive_date_month);
        wvDay = (WheelView) dialogView.findViewById(R.id.wv_archive_date_day);

        final String[] yearArray = new String[20];
        for (int i = currentYear; i > currentYear - 20; i--) {
            yearArray[currentYear - i] = "" + i + "年";
            if (date != null && tmpCalendar.get(Calendar.YEAR) == i) {
                yearIndex = currentYear - i;
            }
        }
        ArrayWheelAdapter<String> yearAdapter = new ArrayWheelAdapter<String>(this, yearArray);
        yearAdapter.setTextSize(20);
        wvYear.setViewAdapter(yearAdapter);
        wvYear.setCurrentItem(yearIndex);
        wvYear.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {

            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(ArchiveAddActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        final String[] monthArray = new String[12];
        for (int j = 0; j < 12; j++) {
            monthArray[j] = "" + (j + 1) + "月";
            if (date != null && tmpCalendar.get(Calendar.MONTH) == j) {
                monthIndex = j;
            }
        }
        ArrayWheelAdapter<String> monthAdapter = new ArrayWheelAdapter<String>(this, monthArray);
        monthAdapter.setTextSize(20);
        wvMonth.setViewAdapter(monthAdapter);
        wvMonth.setCurrentItem(monthIndex);
        wvMonth.addScrollingListener(new OnWheelScrollListener() {
            @Override
            public void onScrollingStarted(WheelView wheel) {
            }

            @Override
            public void onScrollingFinished(WheelView wheel) {
                int tmpIndex = wvDay.getCurrentItem();
                int tmpDayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[wvYear.getCurrentItem()].replace("年", "")), wvMonth.getCurrentItem() + 1);
                String[] tmpDayArray = new String[tmpDayOfMonth];
                for (int k = 0; k < tmpDayOfMonth; k++) {
                    tmpDayArray[k] = "" + (k + 1) + "日";
                }
                if (tmpIndex >= tmpDayOfMonth) {
                    tmpIndex = tmpDayOfMonth - 1;
                }
                ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(ArchiveAddActivity.this, tmpDayArray);
                dayAdapter.setTextSize(20);
                wvDay.setViewAdapter(dayAdapter);
                wvDay.setCurrentItem(tmpIndex);
            }
        });

        int dayOfMonth = getDayOfMonth(Integer.parseInt(yearArray[yearIndex].replace("年", "")), monthIndex + 1);
        final String[] dayArray = new String[dayOfMonth];
        for (int k = 0; k < dayOfMonth; k++) {
            dayArray[k] = "" + (k + 1) + "日";
            if (date != null && tmpCalendar.get(Calendar.DATE) == k + 1) {
                dayIndex = k;
            }
        }
        ArrayWheelAdapter<String> dayAdapter = new ArrayWheelAdapter<String>(this, dayArray);
        dayAdapter.setTextSize(20);
        wvDay.setViewAdapter(dayAdapter);
        wvDay.setCurrentItem(dayIndex);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDateDialog.dismiss();
            }
        });
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String txtYear = yearArray[wvYear.getCurrentItem()].replace("年", ""),
                        txtMonth = "0" + (wvMonth.getCurrentItem() + 1),
                        txtDay = "0" + (wvDay.getCurrentItem() + 1);
                txtMonth = txtMonth.substring(txtMonth.length() - 2);
                txtDay = txtDay.substring(txtDay.length() - 2);

                Calendar now = Calendar.getInstance();
                int year = now.get(Calendar.YEAR);
                int month = (now.get(Calendar.MONTH) + 1);
                int day = now.get(Calendar.DAY_OF_MONTH);
                if (year == Integer.valueOf(txtYear)) {
                    if (month < Integer.valueOf(txtMonth)) {
                        PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "不得超过当前日期");
                    } else if (month == Integer.valueOf(txtMonth) && day < Integer.valueOf(txtDay)) {
                        PhoneUtils.ShowToastMessage(ArchiveAddActivity.this, "不得超过当前日期");
                    } else {
                        etDate.setText(txtYear + "-" + txtMonth + "-" + txtDay);
                        mDateDialog.dismiss();
                    }
                } else {
                    etDate.setText(txtYear + "-" + txtMonth + "-" + txtDay);
                    mDateDialog.dismiss();
                }
            }
        });
        mDateDialog.setContentView(dialogView);
        mDateDialog.setCancelable(true);
        mDateDialog.setCanceledOnTouchOutside(true);

        Window dialogWindow = mDateDialog.getWindow();
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.width = (int) (mDisplay.getWidth() * 0.86);
        dialogWindow.setAttributes(p);
        mDateDialog.show();
    }

    private int getDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 0);
        return c.get(Calendar.DAY_OF_MONTH);
    }


}
